package navgtor

import (
	"bufio"
	"fmt"
)

func startParse(root *navTree, wt *bufio.Writer) error {
	wt.WriteString("\n")
	wt.WriteString("#### [首页](?file=home-首页)\n")
	wt.WriteString("\n")
	wt.Flush()

	err := parseNavTree(root, wt)
	if err != nil {
		return err
	}

	return nil
}

func parseNavTree(node *navTree, wt *bufio.Writer) error {
	if node.nodeType == NODE_TYPE_ROOT {
		for ind := range node.children {
			err := parseNavTree(node.children[ind], wt)
			if err != nil {
				return err
			}
		}
	} else if node.level == 0 {
		wt.WriteString(fmt.Sprintf("##### %s\n", node.name))
		wt.Flush()
		for ind := range node.children {
			err := parseNavTree(node.children[ind], wt)
			if err != nil {
				return err
			}
		}
		wt.WriteString("\n")
		wt.Flush()
	} else if node.nodeType == NODE_TYPE_FOLDER {
		// 非一级的目录
		for i := 0; i < node.level-1; i++ {
			// 写TAB
			wt.WriteString("\t")
		}
		wt.WriteString(fmt.Sprintf("- **%s**\n", node.name))
		wt.Flush()

		for ind := range node.children {
			err := parseNavTree(node.children[ind], wt)
			if err != nil {
				return err
			}
		}
	} else if node.nodeType == NODE_TYPE_FILE {
		// 文件
		for i := 0; i < node.level-1; i++ {
			wt.WriteString("\t")
		}
		wt.WriteString(fmt.Sprintf("- [%s](?file=%s \"%s\")\n", node.name, node.relPath, node.desc))
		wt.Flush()
	} else {
		// 出错
		return fmt.Errorf("处理navTree出错：[%v]", node)
	}

	return nil
}
